﻿using System.Drawing.Imaging;
using System.Drawing;
using PdfiumViewer;

namespace WidgetsDesign.API.Helper
{
    public class PdfToPicHelper
    {
        // PDF转图片
        public void PdfToPic(string filePath, string outFilePath, ImageFormat image)
        {
            var pdf = PdfDocument.Load(filePath);
            var pdfpage = pdf.PageCount;
            var pagesizes = pdf.PageSizes;
            outFilePath = $"{outFilePath}\\{DateTime.Now.ToString("yyyyMMdd-HHmmss")}";
            for (int i = 1; i <= pdfpage; i++)
            {
                Size size = new Size();
                size.Height = (int)pagesizes[(i - 1)].Height * 10;
                size.Width = (int)pagesizes[(i - 1)].Width * 10;
                //可以把".jpg"写成其他形式 RenderPage(filePath, i, size, picPath);
                string outFile = $"{outFilePath}({i}).{image}";
                RenderPage(filePath, i, size, outFile, image);
            }

        }
        private void RenderPage(string pdfPath, int pageNumber, System.Drawing.Size size, string outputPath, ImageFormat mat, int dpi = 300)
        {
            using (var document = PdfDocument.Load(pdfPath))
            using (var stream = new FileStream(outputPath, FileMode.Create))
            using (var image = GetPageImage(pageNumber, size, document, dpi))
                image.Save(stream, mat);
        }
        private static System.Drawing.Image GetPageImage(int pageNumber, Size size, PdfDocument document, int dpi)
        {
            return document.Render(pageNumber - 1, size.Width, size.Height, dpi, dpi, PdfRenderFlags.Annotations);
        }
    }
}
